#!/usr/bin/env python3
"""
工具函数
"""

import logging
import sys
from pathlib import Path


def setup_logger(log_config):
    """
    设置日志

    Args:
        log_config: 日志配置字典

    Returns:
        logging.Logger: 配置好的日志对象
    """
    logger = logging.getLogger('transcriber')
    logger.setLevel(getattr(logging, log_config['level']))

    # 控制台处理器
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(logging.INFO)
    console_format = logging.Formatter('%(levelname)-8s %(message)s')
    console_handler.setFormatter(console_format)
    logger.addHandler(console_handler)

    # 文件处理器
    if log_config.get('file'):
        log_file = Path(log_config['file'])
        log_file.parent.mkdir(parents=True, exist_ok=True)

        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        file_handler.setLevel(logging.DEBUG)
        file_format = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        )
        file_handler.setFormatter(file_format)
        logger.addHandler(file_handler)

    return logger


class PathProxy:
    """
    路径代理类

    支持路径前缀替换，类似前端的代理配置
    """

    def __init__(self, proxy_config):
        """
        初始化路径代理

        Args:
            proxy_config: 代理配置字典
                {
                    "/api/": {
                        "target": "/real/path/",
                        "rewrite": true
                    }
                }
        """
        self.proxy_config = proxy_config or {}

    def resolve(self, path):
        """
        解析路径，应用代理规则

        Args:
            path: 原始路径

        Returns:
            str: 解析后的实际路径

        示例:
            >>> proxy = PathProxy({"/api/": {"target": "/data/", "rewrite": True}})
            >>> proxy.resolve("/api/video.mp4")
            '/data/video.mp4'
        """
        # 尝试匹配代理规则
        for prefix, config in self.proxy_config.items():
            if path.startswith(prefix):
                target = config['target']
                rewrite = config.get('rewrite', True)

                if rewrite:
                    # 替换前缀
                    return path.replace(prefix, target, 1)
                else:
                    # 追加到目标路径
                    return target + path

        # 没有匹配的代理规则，返回原路径
        return path


class TranscriptionError(Exception):
    """转录错误基类"""
    pass


class FileNotFoundError(TranscriptionError):
    """文件不存在错误"""
    pass


class ModelError(TranscriptionError):
    """模型错误"""
    pass
